/*
 * Copyright (c) 2009 John Pritchard, WTKX Project Group
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package wtkx.ui;


/**
 * Produce and cache <code>"*"</code> strings. 
 * @author jdp
 */
public final class Password
    extends Object
{
    private final static Password Cache = new Password();
    /**
     * Skip cache
     */
    public final static String Create(int count){
        return Create(count,'*');
    }
    public final static String Create(int count, char ch){
        if (-1 < count){
            char[] ary = new char[count];
            for (int cc = 0; cc < count; cc++){
                ary[cc] = ch;
            }
            return new String(ary);
        }
        else
            return null;
    }
    /**
     * Use cache
     */
    public final static String Get(int count){
        return Cache.get(count);
    }


    private String[] cache;


    public Password(){
        super();
    }


    public String get(int count){
        String[] cache = this.cache;
        if (-1 < count){
            if (null == cache){
                String re = Create(count);
                synchronized(this){
                    cache = new String[count+1];
                    this.cache = cache;
                    cache[count] = re;
                }
                return re;
            }
            else if (count < cache.length){
                String re = cache[count];
                if (null != re)
                    return re;
                else {
                    re = Create(count);
                    synchronized(this){
                        cache[count] = re;
                    }
                    return re;
                }
            }
            else {
                synchronized(this){
                    String[] copier = new String[count+1];
                    System.arraycopy(cache,0,copier,0,cache.length);
                    this.cache = copier;
                }
                String re = Create(count);
                this.cache[count] = re;
                return re;
            }
        }
        else
            return null;
    }

}
